import React, { useEffect, useState } from "react";
import {
  NavLink,
  Route,
  Routes,
  useRoutes,
  Navigate,
  useLocation,
} from "react-router-dom";

import Home from "./pages/Home"; // /home
import About from "./pages/About"; // /about
import Help from "./pages/Help"; // /help
import Login from "./pages/Login"; // /login
import HomeHello from "./pages/HomeHello"; // /home/hello
import HomeWorld from "./pages/HomeWorld"; // /home/world

const links = [
  { id: 1, name: "Home", path: "/home" },
  { id: 2, name: "About", path: "/about" },
  { id: 3, name: "Help", path: "/help" },
  { id: 4, name: "Login", path: "/login" },
];

function AuthCheck({ children }) {
  // 获取到跳转前的url地址
  const location = useLocation();
  console.log("AuthCheck", location);
  // 判断有没有登录
  const token = window.localStorage.getItem("token");
  if (token) {
    return children;
  } else {
    // 这里使用替换模式，不然后退不了
    // 不用 replace /home -> /help -> 没有登录 -> /login
    // 使用 replace /home -> /login
    return <Navigate to={`/login?redirect=${location.pathname}`} replace />;
  }
}

function App() {
  console.log("App");
  const element = useRoutes([
    {
      path: "/home",
      element: <Home />,
      children: [
        {
          path: "hello",
          element: <HomeHello />,
        },
        {
          path: "world",
          element: <HomeWorld />,
        },
      ],
    },
    {
      path: "/about",
      element: (
        <AuthCheck>
          <About />
        </AuthCheck>
      ),
    },
    {
      path: "/help",
      element: (
        <AuthCheck>
          <Help />
        </AuthCheck>
      ),
    },
    {
      path: "/login",
      element: <Login />,
    },
  ]);
  return (
    <div className="app">
      <div className="header">头部</div>
      <div className="main">
        <div className="left">
          <ul>
            {links.map((item) => {
              return (
                <li key={item.id}>
                  <NavLink className="link" to={item.path}>
                    {item.name}
                  </NavLink>
                </li>
              );
            })}
          </ul>
        </div>
        {/* <div className="right">
          <Routes>
            <Route path="/home" element={<Home />}>
              <Route path="hello" element={<HomeHello />} />
              <Route path="world" element={<HomeWorld />} />
            </Route>
            <Route
              path="/about"
              element={
                <AuthCheck>
                  <About />
                </AuthCheck>
              }
            />
            <Route
              path="/help"
              element={
                <AuthCheck>
                  <Help />
                </AuthCheck>
              }
            />
            <Route path="/login" element={<Login />} />
          </Routes>
        </div> */}

        <div className="right">{element}</div>
      </div>
    </div>
  );
}

export default App;
